package logic

import (
	"context"
	"encoding/json"
	"hema/cache"
	"hema/models"
	"time"

	"hema/hemarpc/hemarpc"
	"hema/hemarpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProductListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProductListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductListLogic {
	return &ProductListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ProductListLogic) ProductList(in *hemarpc.ProductListRequest) (*hemarpc.ProductListResponse, error) {
	// todo: add your logic here and delete this line
	var products []models.Product

	list := "list"

	result, _ := cache.Rdb.Get(l.ctx, "productList").Result()
	if result == "" {
		models.DB.Debug().Model(&models.Product{}).
			Select("products.*,class.`name` as class_name").
			Joins("left join classes on products.classes_id").
			Find(products)

		marshal, _ := json.Marshal(products)
		cache.Rdb.Set(l.ctx, list, marshal, time.Minute*30)
	} else {
		json.Unmarshal([]byte(result), &products)
	}

	var productLists []*hemarpc.ProductList

	for _, product := range products {
		list := hemarpc.ProductList{
			Name:      product.Name,
			Price:     float32(product.Price),
			Stock:     product.Stock,
			Image:     product.Image,
			Info:      product.Info,
			ClassName: "",
			ProductId: int64(product.ID),
		}

		productLists = append(productLists, &list)
	}

	return &hemarpc.ProductListResponse{
		List: productLists,
	}, nil
}
